package com.Bigbluebook.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.Bigbluebook.Activity.ConversationActivity;
import com.Bigbluebook.R;
import com.Bigbluebook.Service.FollowApiService;
import com.Bigbluebook.Service.MessageApiService;
import com.Bigbluebook.Service.UserApiService;
import com.Bigbluebook.adapter.MessageAdapter;
import com.Bigbluebook.entity.ApiResponse;
import com.Bigbluebook.entity.Follow;
import com.Bigbluebook.entity.Message;
import com.Bigbluebook.entity.User;

import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MessageFragment extends Fragment {
    private RecyclerView recyclerView;
    private MessageAdapter adapter;
    private List<User> users = new ArrayList<>();
    private List<Follow> follows = new ArrayList<>(); // 定义关注者列表
    private int userid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        userid = sharedPreferences.getInt("userid", -1); // 确保使用正确的类型
        recyclerView = view.findViewById(R.id.messagesRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        adapter = new MessageAdapter(users); // 使用声明的adapter变量
        adapter.setOnItemClickListener(new MessageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(User user) {
                // 跳转到对话页面
                Intent intent = new Intent(getContext(), ConversationActivity.class);
                intent.putExtra("userId", (long)user.getId()); // 假设 ConversationActivity 需要用户ID
                Log.e("用户信息","id是" + user.getId());
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(adapter);

        loadFollowersMessages();

        return view;
    }

    private void loadFollowersMessages() {
        FollowApiService followApiService = new FollowApiService();
        followApiService.getFollowers(userid, new Callback<ApiResponse<List<Follow>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<Follow>>> call, Response<ApiResponse<List<Follow>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<Follow> follows = response.body().getData();
                    if (follows != null) {
                        getUsersInfo(follows);
                    } else {
                        Log.e("关注者", "没有关注者数据");
                    }
                } else {
                    Log.e("关注者接口", response.toString());
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<Follow>>> call, Throwable t) {
                Log.e("关注者接口", "网络请求失败: " + t.getMessage());
                Toast.makeText(getContext(), "获取关注者列表失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getUsersInfo(final List<Follow> follows) {
        for (final Follow follow : follows) {
            UserApiService userService = new UserApiService();
            userService.getUser(follow.getFolloweeId(), new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        users.add(response.body());
                        if (users.size() == follows.size()) {
                            // 所有用户信息加载完毕，更新UI
                            updateFollowers();
                        }
                    } else {
                        Log.e("用户信息", response.toString());
                    }
                }

                @Override
                public void onFailure(Call<User> call, Throwable t) {
                    Log.e("用户信息", "网络请求失败: " + t.getMessage());
                }
            });
        }
    }

    private void updateFollowers() {
        // 此处应确保在UI线程中执行
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.setUsers(users); // 更新适配器中的数据
            }
        });
    }
}